<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/2/7
 * Time: 23:56
 */
declare(strict_types=1);

namespace App\Service;
use App\Model\Dao\MchAccountAccessDao;
use App\Model\Dao\MchAccountAccessDetailDao;
use App\Model\Dao\MchAccountDao;
use App\Model\Dao\RateSettleDao;
use App\Model\Dao\TradeOrderDetailDao;
use App\Model\Dao\TradeOrderThawDao;
use App\Utils\CustomUtils;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Exception;

/**
 * Class SettleTradeOrderThawService
 * @package App\Service
 * 交易订单解解冻算
 */
class SettleTradeOrderThawService extends CommonService
{

    /**
     * @Inject()
     * @var TradeOrderThawDao
     */
    private $TradeOrderThawDao;

    /**
     * @Inject()
     * @var TradeOrderDetailDao
     */
    private $TradeOrderDetailDao;

    /**
     * @Inject()
     * @var MchAccountDao
     */
    private $MchAccountDao;

    /**
     * @Inject()
     * @var MchAccountAccessDao
     */
    private $MchAccountAccessDao;

    /**
     * @Inject()
     * @var MchAccountAccessDetailDao
     */
    private $MchAccountAccessDetailDao;

    /**
     * @Inject()
     * @var RateSettleDao
     */
    private $RateSettleDao;

    public function handle($param) {
        // 校验
        $tradeOrderThaw = $this->TradeOrderThawDao->get($param['thawId']);
        if(!$tradeOrderThaw) {
            throw new Exception('解冻单不存在，终止处理', FAILED_CODE);
        }
        if($tradeOrderThaw['handleStatus'] != $param['handleStatus']) {
            throw new Exception('解冻单处理状态不对应', FAILED_CODE);
        }
        if($tradeOrderThaw['settleStatus'] == 1) {
            throw new Exception('解冻单已解冻结算完成', FAILED_CODE);
        }
        $tradeOrder = $this->TradeOrderDetailDao->get($tradeOrderThaw['orderId']);
        if($tradeOrder['isSettle'] != 2) {
            throw new Exception('解冻单原始交易订单未结算', FAILED_CODE);
        }
        $mchAccount = $this->MchAccountDao->get($param['mchAccountId']);
        if(!$mchAccount) {
            throw new Exception('查询账户记录失败', FAILED_CODE);
        }

        // 初审通过不用管
        if ($param['handleStatus'] != 3) {
            return $this->handleFirstConfirm($tradeOrderThaw);
        }
        return $this->handleConfirm($param, $tradeOrder, $tradeOrderThaw, $mchAccount);
    }

    private function handleFirstConfirm($tradeOrderThaw) {
        Db::beginTransaction();
        try {
            $this->TradeOrderThawDao->set($tradeOrderThaw['id'], [
                'settleStatus'  => 1,
            ]);
        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();
            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易订单解冻初审结算失败");
        }
        Db::commit();
        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易订单解冻初审通过结算成功");
    }

    /**
     * @param $param
     * @param $tradeOrder
     * @param $tradeOrderThaw
     * @param $mchAccount
     * @return array
     * @throws Exception
     * 解冻单，审核，出入账
     */
    private function handleConfirm($param, $tradeOrder, $tradeOrderThaw, $mchAccount) {
        // 乐观锁版本号+1
        $updateVersion = $mchAccount['updateVersion'] + 1;
        $transSettleAmount = $tradeOrderThaw['transSettleAmount'];

        // 交易可提现金额，解冻金额，余额前后
        $beforeThawTradeCashAmount = $mchAccount['tradeCashAmount'];
        $afterThawTradeCashAmount  = $mchAccount['tradeCashAmount'] + $transSettleAmount;

        // 交易解冻金额，解冻金额，余额前后
        $beforeThawTradeFrozenAmount = $mchAccount['tradeFrozenAmount'];
        $afterThawTradeFrozenAmount = $mchAccount['tradeFrozenAmount'] - $transSettleAmount;

        // 开启事务
        Db::beginTransaction();
        try {
            // step
            // 1.解冻交易解冻出账
            // 2.解冻交易可提现入账
            // 3.更新解冻订单结算状态
            // 8.更新账户

            // step 1
            $this->handleConfirmFrozenOutTransAmount($param, $tradeOrderThaw, $mchAccount, $transSettleAmount, $beforeThawTradeFrozenAmount, $afterThawTradeFrozenAmount);

            // step 2
            $this->handleConfirmCashInTransAmount($param, $tradeOrderThaw, $mchAccount, $transSettleAmount, $beforeThawTradeCashAmount, $afterThawTradeCashAmount);

            // step 3
            $this->TradeOrderThawDao->set($tradeOrderThaw['id'], [
                'settleStatus'  => 1,
                'settleTime'    => time()
            ]);

            // step 4
            $updateMchAccount = array(
                "tradeCashAmount"   => $afterThawTradeCashAmount,
                "tradeFrozenAmount" => $afterThawTradeFrozenAmount,
                "updateVersion"     => $updateVersion
            );
            $result = $this->MchAccountDao->updateWhere([
                "id" => $param['mchAccountId'],
                "updateVersion" => $mchAccount['updateVersion']
            ], $updateMchAccount);

            // 如果更新账户失败，重试，最多3次
            if (!$result) {
                throw new \Exception("更新账户失败");
            }

        } catch (\Throwable $e) {
            CustomUtils::xzxDebug($e->getMessage());
            Db::rollBack();

            // 失败重试，最多3次
            $this->tryOneMore($param);

            return CustomUtils::xeServiceReturnData(FAILED_CODE, "交易解冻单审核结算失败");
        }
        Db::commit();

        return CustomUtils::xeServiceReturnData(SUCCESS_CODE, "交易解冻单审核结算成功");
    }

    /**
     * @param $param
     * @param $tradeOrderThaw
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 审核，解冻金额，可提现入账
     */
    private function handleConfirmCashInTransAmount($param, $tradeOrderThaw, $mchAccount, $amount, $beforeAmount, $afterAmount) {

        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $tradeOrderThaw["mchId"],
            "mchNo"        => $tradeOrderThaw["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_TRADE_ORDER_THAW,
            "accountType"  => ACCOUNT_TYPE_CASH,
            "orderId"      => $tradeOrderThaw['orderId'],
            "tradeNo"      => $tradeOrderThaw['tradeNo'],
            "thawId"       => $tradeOrderThaw['id'],
            "amount"       => $amount,
            "currency"     => $tradeOrderThaw['transSettleCurrency'],
            "status"       => 1,
            "remark"       => "交易订单解冻",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderThaw["mchId"],
            "mchNo"             => $tradeOrderThaw["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH,
            "inOutType"         => DETAIL_TYPE_IN,
            "type"              => TYPE_TRADE_ORDER_THAW_CONFIRM_CASH_IN,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => $amount,
            "currency"          => $tradeOrderThaw['transSettleCurrency'],
            "orderId"           => $tradeOrderThaw['orderId'],
            "tradeNo"           => $tradeOrderThaw['tradeNo'],
            "thawId"            => $tradeOrderThaw['id'],
            "remark"            => "交易订单解冻解冻可提现账户入账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }

    /**
     * @param $param
     * @param $tradeOrderThaw
     * @param $mchAccount
     * @param $amount
     * @param $beforeAmount
     * @param $afterAmount
     * 确认，解冻金额，解冻金额出账
     */
    private function handleConfirmFrozenOutTransAmount($param, $tradeOrderThaw, $mchAccount, $amount, $beforeAmount, $afterAmount) {
        // 写主表
        $mchAccountAccess = array(
            "id"           => CustomUtils::createUUID(),
            "mchId"        => $tradeOrderThaw["mchId"],
            "mchNo"        => $tradeOrderThaw["mchNo"],
            "mchAccountId" => $param['mchAccountId'],
            "accessType"   => ACCESS_TYPE_TRADE_ORDER_THAW,
            "accountType"  => ACCOUNT_TYPE_CASH_FROZEN,
            "orderId"      => $tradeOrderThaw['orderId'],
            "tradeNo"      => $tradeOrderThaw['tradeNo'],
            "thawId"       => $tradeOrderThaw['id'],
            "amount"       => -$amount,
            "currency"     => $tradeOrderThaw['transSettleCurrency'],
            "status"       => 1,
            "remark"       => "交易订单解冻",
            "createTime"   => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDao->add($mchAccountAccess);

        // 写明细表
        $mchAccountAccessDetail = array(
            "id"                => CustomUtils::createUUID(),
            "mchId"             => $tradeOrderThaw["mchId"],
            "mchNo"             => $tradeOrderThaw["mchNo"],
            "mchAccountId"      => $param['mchAccountId'],
            "accessId"          => $mchAccountAccess['id'],
            "accountType"       => ACCOUNT_TYPE_CASH_FROZEN,
            "inOutType"         => DETAIL_TYPE_OUT,
            "type"              => TYPE_TRADE_ORDER_THAW_CONFIRM_FROZEN_OUT,
            "beforeTotalAmount" => $beforeAmount,
            "afterTotalAmount"  => $afterAmount,
            "amount"            => -$amount,
            "currency"          => $tradeOrderThaw['transSettleCurrency'],
            "orderId"           => $tradeOrderThaw['orderId'],
            "tradeNo"           => $tradeOrderThaw['tradeNo'],
            "thawId"            => $tradeOrderThaw['id'],
            "remark"            => "交易订单解冻解冻解冻账户出账",
            "createTime"        => CustomUtils::xzxGetMsecTime()
        );
        $this->MchAccountAccessDetailDao->add($mchAccountAccessDetail);
    }
}